首页 > 试题广场 >

一种字符串和数字的对应关系

[编程题]一种字符串和数字的对应关系
  • 热度指数:534 时间限制:C/C++ 2秒,其他语言4秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
一个char类型的数组chs,其中所有的字符都不同。
例如,chs = ['A', 'B', 'C', ... 'Z'],则字符串与整数的对应关系如下:
A,  B...Z, AA, AB... AZ, BA,BB...ZZ, AAA...ZZZ,    AAAA... 
1,  2, .26,27,  28,... 52, 53. 54...702,703... 18278, 18279.
例如,chs=['A','B','C'],则字符串与整数的对应关系如下:
A, B, C, AA, AB...CC, AAA...CCC, AAAA....
1   2  3     4     5    12      13      39        40
给定一个数组chs, 实现根据对应关系完成字符串与整数相互转换的两个函数
[要求]
数字转字符串的复杂度为,字符串转数字的复杂度为

输入描述:
第一行有里两个个整数opt, base, 分别表示问题类型,chs的长度
接下来一行有base个字符表示字符数组chs。
若opt = 1,则下一行有一个整数N,分别表示对应的数字。
若opt = 2,则下一行有一个字符串,表示需要转化为数字的字符数组


输出描述:
若opt=1,输出一个字符串。否则输出一个整数
示例1

输入

1 3 
ABC
42

输出

AAAC
示例2

输入

2 3
ABC 
AAAC

输出

42
示例3

输入

1 3
ABC
36

输出

CBC
示例4

输入

2 3
ABC
CBC

输出

36

备注:
考虑到不同语言的数字运算范围差异,本题的数据范围与算法复杂度无关


保证输入合法 且 输入字符串长度不超过8 且 字符集内字符两两不同 且 均为大写字母
没劲的题目
class Question1:
    def solve_mode_1(self, base:int, str_chs:str, num:int) -> str:
        len_res = 1
        while True:
            if num > base ** len_res:
                num -= base ** len_res
                len_res += 1
            else:
                break
        num -= 1  # num -> DEC to base
        res = ''
        bit = 0
        while bit < len_res:
            res += str_chs[num % (base)]
            num = num // base
            bit += 1
        return res[::-1]
    
    def solve_mode_2(self, base:int, str_chs:str, str_input:str) -> int:
        num = 0   # start from 0, n base to DEC
        for bit in range(len(str_input)):
            num += str_chs.find(str_input[::-1][bit]) * base ** bit
        for i in range(len(str_input)):
            num += base ** i
        return num


q = Question1()
        
info = list(map(int, input().split(' ')))
opt = info[0]
base = info[1]
str_chs = input()

if opt == 1:
    num = int(input())
    print(q.solve_mode_1(base, str_chs, num))
else:
    str_input = input()
    print(q.solve_mode_2(base, str_chs, str_input))


发表于 2022-09-14 16:49:53 回复(0)